//
//  LWChannelView.m
//  练习项目
//
//  Created by 吴丹草 on 17/1/4.
//  Copyright © 2017年 吴丹草. All rights reserved.
//

#import "LWChannelView.h"
#import "LWChannelModel.h"
#import "LWLabel.h"

static NSInteger baseTag = 100;

@interface LWChannelView ()

@property(nonatomic,strong)UIScrollView *scrollView;


@end


@implementation LWChannelView

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        [self setupUI];
    }
    
    return self;
}

- (void)setupUI
{
    self.backgroundColor = [UIColor greenColor];
    _scrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
    [self addSubview:_scrollView];
    
}

- (void)setTitleList:(NSArray *)titleList
{
    CGFloat originX = 0;
    NSInteger index = 0;
    
    
    //用title创建label
    for (LWChannelModel *model in titleList)
    {
        LWLabel *label = [LWLabel addLabelWithTitle:model.tname];
        label.userInteractionEnabled = YES;
 
        if(index == 0)
        {
            label.isSelect = YES;
        }
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
        
        [label addGestureRecognizer:tap];

        
        label.tag = index + baseTag;
        
        CGRect frame = CGRectMake(originX, 0, label.bounds.size.width, self.bounds.size.height);
        label.frame = frame;
        [_scrollView addSubview:label];
        
        originX += label.bounds.size.width;
        index += 1;
        
        
          }
    
    _scrollView.contentSize = CGSizeMake(originX, 1);
}

- (void)setCurrentIndex:(NSInteger)currentIndex
{
    LWLabel *label = (LWLabel *)[_scrollView viewWithTag:currentIndex+baseTag];
    label.isSelect = YES;
    
    
    if(_currentIndex == currentIndex)
    {
        return;
    }
    
    CGFloat labelX = label.bounds.origin.x;
    CGFloat labelOffSet = label.bounds.size.width + labelX;
    CGFloat scrollViewX = _scrollView.contentOffset.x;
    
    if(labelX < scrollViewX || labelOffSet > scrollViewX)
    {
      
        [_scrollView scrollRectToVisible:label.frame animated:YES];
    }
    
    LWLabel *oldLabel = [_scrollView viewWithTag:_currentIndex+baseTag];
    oldLabel.isSelect = NO;
    
    _currentIndex = currentIndex;
}

- (void)tapClick : (UITapGestureRecognizer *)sender
{
    LWLabel *label = (LWLabel *)sender.view;
    NSInteger index = label.tag - baseTag;
    [self setCurrentIndex:index];
    if(_delegate != nil && [_delegate respondsToSelector:@selector(channelView:sendWithIndex:)])
    {
        [_delegate channelView:self sendWithIndex:index];
    }
    
    NSLog(@"==%zd",index);
    
}

@end
